<!-- 会员管理 
 从分页组件传了两个事件过来changLimit、changPage
-->
<template>
    <div class="main" @scroll.passive="scrollTop($event)">
         <!-- 会员管理头部 -->
        <div class="member-top">
            <el-space wrap :size="10">
                <el-select v-model="searchData.userStatus" placeholder="请选择用户状态"  @clear="searchData.userStatus=undefined" style="width: 10vw;" clearable>
                    <el-option label="冻结" :value="0">冻结</el-option>
                    <el-option label="激活" :value="1">激活</el-option>
                    <el-option label="全部" value="">全部</el-option>
                </el-select>
                <el-select v-model="searchData.userLevel" placeholder="请选择会员等级"  @clear="searchData.userLevel=undefined" style="width: 10vw;" clearable>
                    <el-option label="普通会员" :value="0">普通会员</el-option>
                    <el-option label="VIP会员" :value="1">VIP会员</el-option>
                    <el-option label="全部" value="">全部</el-option>
                </el-select>
                <el-select v-model="searchData.userGender" placeholder="请选择用户性别"   @clear="searchData.userGender=undefined" style="width: 10vw;" clearable>
                    <el-option label="男" :value="2">男</el-option>
                    <el-option label="女" :value="1">女</el-option>
                    <el-option label="全部" value="">全部</el-option>
                </el-select>
                <el-input v-model="searchData.userId" placeholder="请输入用户ID" clearable
                    @keyup.enter.native="handlresearch" />
                <el-input v-model="searchData.userNickname" placeholder="请输入昵称" clearable
                    @keyup.enter.native="handlresearch" />
                <el-button type="primary" :icon="Search" @click="handlresearch">查找</el-button>
            </el-space>
        </div>
         <!-- 会员列表 -->
        <div class="member-table">
            <el-table :data="tableData" border style="width: 100%;">
                <el-table-column prop="id" label="用户ID" align="center" sortable width="100" />
                <el-table-column prop="nickname" label="昵称" align="center" />
                <el-table-column prop="phone" label="电话" align="center" />
                <el-table-column prop="gender" label="性别" align="center" width="80">
                    <template #default="scope">
                        <el-tag>{{scope.row.gender==1?'女':'男'}}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="level" label="会员等级" align="center">
                    <template #default="scope">
                        <el-tag :type="scope.row.level==1?'warning':'info'">{{scope.row.level==1?'VIP会员':'普通会员'}}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="birthday" label="生日" align="center">
                    <template #default="scope">
                        <template v-if="scope.row.birthday">
                            {{new Date(scope.row.birthday).friendTime(1).split(' ')[0]}}
                        </template>
                        <template v-else>
                             <span>-</span>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" align="center" width="80">
                    <template #default="scope">
                        <el-tag :type="scope.row.status==0?'danger':''">{{scope.row.status==0?'冻结':'激活'}}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="gmtLastLogin" label="上次登录时间" align="center" width="200">
                    <template #default="scope">
                        {{new Date(scope.row.gmtLastLogin).friendTime()}}
                    </template>
                </el-table-column>
                <el-table-column prop="lastLoginIp" label="上次登录IP" align="center" width="100" />
                <el-table-column label="操作" align="center">
                    <template #default="scope">
                        <el-button :type= "scope.row.status==0?'primary':'danger'" @click="handlerActivation(scope.row)">{{scope.row.status==0?'激活':'冻结'}}</el-button>
                        <el-button type="primary" @click="handlerEdit(scope.row)">编辑</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 添加和修改弹出框 -->
            <el-dialog v-model="dialogFormVisible" :title="bool?'创建':'修改'" destroy-on-close>
                <el-form :model="form" status-icon :rules="rules" ref="ruleFormRef">
                    <el-form-item label="用户昵称" prop="nickname" class="is-required">
                        <el-input v-model.trim="form.nickname" autocomplete="off" :disabled="bool==false" />
                    </el-form-item>
                    <el-form-item label="用户手机号" prop="phone" class="is-required" v-if="bool">
                        <el-input v-model.trim="form.phone" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="用户性别" class="is-required" prop="gender">
                        <el-select v-model="form.gender" class="m-2" placeholder="请选择" clearable>
                            <el-option label="男" :value="2">男</el-option>
                            <el-option label="女" :value="1">女</el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="用户等级" class="is-required" prop="level">
                        <el-select v-model="form.level" class="m-2" placeholder="请选择" clearable>
                            <el-option label="普通会员" :value="0">普通会员</el-option>
                            <el-option label="VIP会员" :value="1">VIP会员</el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="用户状态" prop="status" class="is-required">
                        <el-select v-model="form.status" class="m-2" placeholder="请选择" clearable>
                            <el-option label="冻结" :value="0">冻结</el-option>
                            <el-option label="激活" :value="1">激活</el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogFormVisible = false">取消</el-button>
                        <el-button type="primary" @click="handleEditOk(ruleFormRef)">修改</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
        <!-- 分页组件 -->
        <div>
            <Paging v-bind="pagingDatas" @page-change="pageChange"></Paging>
        </div>
        <el-backtop :right="100" :bottom="100" ref="main" target=".main" :visibility-height="0" v-if="bool" />
    </div>
</template>
<script  setup lang="ts">
import { nextTick, reactive, ref, watch } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ClassPagination } from "#/index";
import Paging from "@/components/paging/Paging.vue";
import { get } from "@/utils/request";
import { ElMessage } from 'element-plus'
import "@/utils/dataFriend"
import type { FormInstance } from 'element-plus'
const ruleFormRef = ref<FormInstance>()
let main = ref()  //滚动组件对象的引用
let rollHeight = ref(0)  //滚动距离
let bool = ref(true)  //用来判断滚动组件的显示隐藏
let tableData: TypeMember[] = reactive([])
const dialogFormVisible = ref(false) //控制修改框是否可见
//增加弹出框数据
const form: TypeMember = reactive({
    nickname: '',  //用户昵称
    gender: 2,  //用户性别
    phone: "",  //用户手机号
    level: 0, //用户等级
    id: 0,
    status: 0,//用户状态
})

const searchData = reactive({
    userNickname: "", //用户名称搜索框
    userId: '', //用户id搜索框 
    userStatus: undefined,//用户状态
    userGender: undefined,//用户性别
    userLevel: undefined,//用户会员
})

let newsearchData = { ...searchData }
//分页数据
let pagingDatas = reactive(new ClassPagination())
//会员列表
function loadMemberList() {
    let data = {
        _gp: 'admin.user',
        _mt: "list",
        id: newsearchData.userId,
        nickname: newsearchData.userNickname,
        level: newsearchData.userLevel,
        gender: newsearchData.userGender,
        status: newsearchData.userStatus,
        pageNo: pagingDatas.page,
        limit: pagingDatas.limit
    }
    console.log(data)
    get(data).then((res) => {
        console.log(res)
        if (200 == res.errno) {
            tableData.length = 0
            tableData.push(...res.data.items)
            pagingDatas.total = res.data.total
        }
    })
}
//用户名验证
const validateUser = (rule: object, value: string, callback: Function) => {
    if ('' === value) {
        return callback(new Error('用户名不能为空'))
    } else {
        callback()
    }
}
//电话验证
const validatePhone = (rule: object, value: string, callback: Function) => {
    var phone = /^((13[0-9])|(14[5|7])|(15([0-8]|[5-9]))|(18[0,5-9])|(19[0,2-9]))\d{8}$/;
    if ('' === value) {
        callback(new Error('电话号码不能为空'))
    } else if (!phone.test(value)) {
        callback(new Error('电话号码不存在'))
    } else {
        callback()
    }
}
//角色验证
const validateStatus = (rule: object, value: string, callback: Function) => {
    if ('' === value) {
        callback(new Error('不能为空'))
    } else {
        callback()
    }
}
//失焦触发验证
const rules = reactive({
    nickname: [{ validator: validateUser, trigger: 'blur' }],
    gender: [{ validator: validateStatus, trigger: 'change' }],
    level: [{ validator: validateStatus, trigger: 'change' }],
    phone: [{ validator: validatePhone, trigger: 'blur' }],
    status: [{ validator: validateStatus, trigger: 'change' }],
})

//** 搜索 */
function handlresearch() {
    Object.assign(newsearchData, searchData)
    loadMemberList()
}

/**
 * 激活
 *  @param row 当前对象
 */
function handlerActivation(row: TypeMember) {
    let data = {
        _gp: 'admin.user',
        _mt: 'editStatus',
        userId: row.id,
        status: row.status == 1 ? 0 : 1
    }
    get(data).then((res => {
        if (200 == res.errno) {
            ElMessage.success("修改成功")
            loadMemberList()
        } else {
            ElMessage.error(res.errmsg)
        }
    }))
}

/**
 * 修改
 */
function handlerEdit(row: TypeMember) {
    dialogFormVisible.value = true
    Object.assign(form, row) //合并row对象
}

/**
 * 修改确定
 */
function handleEditOk(formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            let data = {
                _gp: "admin.user",
                _mt: "edit",
                user: { ...form }
            }
            get(data).then((res) => {
                if (200 == res.errno) {
                    ElMessage.success("修改成功")
                    dialogFormVisible.value = false
                    loadMemberList()
                } else {
                    ElMessage.success(res.errmsg)
                }
            })
        } else {
            console.log('error submit!')
            ElMessage.error("修改失败")
            return false
        }
    })
}

function pageChange(e: TypePaGing) {
    pagingDatas.page = e._page
    pagingDatas.limit = e._limit
    loadMemberList()
    nextTick(() => {
        main.value.$el.click?.()
    })
}

//滚动事件
let scrollTop = (e: Event) => {
    rollHeight.value = Math.floor((e.target as EventTarget).scrollTop)
}
//监听滚动的距离
watch(rollHeight, (val: number) => {
    //    console.log(val);
    bool.value = val > 60
})
loadMemberList()
</script>
<style scoped lang="less">
.member-top {
    margin: 15px 0px;

    .el-input {
        width: 11vw;
    }
}

.member-table {
    .el-dialog {
        .el-form {
            text-align: center;

            &::v-deep .el-form-item__label {
                width: 12vw;
            }

            .el-form-item__content {
                .el-input {
                    width: 25vw;
                }
            }
        }
    }
}
</style>